import React from "react";
import classnames from "classnames";
import { toJS } from "mobx";
import { inject, observer } from "mobx-react";
import { withRouter, Link } from "react-router-dom";
import { Icon, Tools, Popover, Tag, SearchBar } from "weaver-mobile";
import {
  SearchPage,
  SearchAdvanced,
  ListViewPage,
  RouteLayout,
} from "weaver-mobile-page";
import { renderIsTop, renderLoading, renderNoData } from "../public";
import { getFontColorFromBgHex, PARAMS, compareParams } from "../../util";
import RouteModal from "./RouteModal";
import BackTop from "../../public/back-to-top";
import CustomSelect from "../../public/cowork-select";

const getLabel = Tools.getLabel;
const ButtonGroup = RouteLayout.ButtonGroup;

@withRouter
@inject("communicationStore")
@observer
export default class Communication extends React.Component {
  static defaultProps = {
    prefixCls: "cowork-communication",
  };
  constructor(props) {
    super(props);
    this.state = {
      page: "",
      pathname: props.location.pathname,
    };
  }

  componentWillMount() {
    const { communicationStore } = this.props;
    const { inital } = communicationStore;
    this.setActivePage();
    inital();
  }

  componentDidMount() {
    const { communicationStore } = this.props;
    const {
      getCoworkList,
      getParams,
      activePage,
      setStoreState,
      coworkAdSearchStore,
      coworkJoinType,
      getCoworkViewType,
    } = communicationStore;
    if (coworkAdSearchStore) {
      let searchParams = getParams(activePage);
      coworkAdSearchStore
        .getData({
          url: "/api/cowork/base/getCoworkItemRecordCondition",
          method: `GET`,
          params: { ...PARAMS },
        })
        .then(async (form) => {
          for (var item of toJS(form.conditioninfo[0].items)) {
            if (item.domkey == "labelid") {
              setStoreState({ labelOption: toJS(item.options) });
              break;
            }
          }
          let res = await getCoworkViewType();
          if (activePage === "communication") {
            form.updateFields({ jointype: { value: res.joinType } });
            setStoreState({ coworkJoinType: res.joinType });
          } else {
            form.updateFields({ jointype: { value: searchParams } });
            setStoreState({ coworkJoinType: searchParams });
          }
          getCoworkList();
        });
    } else {
      getCoworkList();
    }
  }

  componentWillReceiveProps(preProps) {
    // 新建协作、标记为页面返回 重新刷新列表
    const {
        location: { pathname },
        history,
      } = preProps,
      { location } = this.props;
    const {
      communicationStore: { coworkListStore, getCoworkList },
    } = this.props;
    if (
      (location.pathname.indexOf("/createCowork") > -1 ||
        location.pathname.indexOf("/tag") > -1) &&
      this.state.pathname.indexOf(pathname) > -1 &&
      history.action === "POP"
    ) {
      coworkListStore.clearData();
      getCoworkList();
    }
  }

  componentWillUnmount() {
    const {
      communicationStore: { clear },
    } = this.props;
    clear();
  }

  setActivePage(props) {
    const {
      location: { pathname },
      communicationStore: { setStoreState },
    } = props || this.props;
    if (/^\/[^/]+\/?/.test(pathname)) {
      const active =
        (pathname.match(/^\/center\/([^/]+)/) &&
          pathname.match(/^\/center\/([^/]+)/)[0].replace(/^\/center\//, "")) ||
        pathname.match(/^\/[^/]+/)[0].replace(/^\//, "");
      setStoreState({ activePage: active, path: this.props.match.path });
      this.setState({ page: active });
    }
  }

  // popover 选择操作
  onSelect = (node, index) => {
    const {
      communicationStore: { setStoreState, path },
    } = this.props;
    const commonFuc = () => setStoreState({ visible: false });
    switch (index) {
      case 0: {
        commonFuc();
        this.props.history.push(`${path}/createCowork`);
        break;
      }
      case 1: {
        commonFuc();
        this.props.history.push(`${path}/manage`);
        break;
      }
      case 2: {
        commonFuc();
        // todo 批量标记
        setStoreState({ showCheck: true });
        break;
      }
      default:
        break;
    }
  };

  /* 跳转详情页 */
  toDetailCowork = (v) => {
    this.props.history.push(
      `${this.props.location.pathname}/detail?id=${v.id}`
    );
  };

  onSearchAdvancedReset = () => {
    const { communicationStore } = this.props;
    const {
      getParams,
      activePage,
      coworkAdSearchStore,
      setStoreState,
    } = communicationStore;
    let searchParams = getParams(activePage);
    coworkAdSearchStore.form.resetFields();
    coworkAdSearchStore.form.updateFields({
      jointype: { value: searchParams },
    });
    setStoreState({ coworkSearchValue: "" });
  };

  // 自定义渲染模板
  getTemplate = (template) => {
    const { prefixCls } = this.props;
    const newTemp = {
      ...template,
      json: [
        {
          key: "col_1",
          render: (data) => {
            const {
              name,
              isTop,
              important,
              isnew,
              lastdiscussantspan,
              id_strspan,
              id,
              approvalAtatus /* hrmDataspan */,
            } = data;
            let labelBycoworkList = JSON.parse(id_strspan);
            return (
              <div className={`${prefixCls}-coworkList-line`} key={id}>
                <div className={`${prefixCls}-coworkList-line-info`}>
                  <span
                    className={`${prefixCls}-coworkList-line-name`}
                    style={{ fontWeight: isnew === "1" ? 700 : 400 }}
                  >
                    {approvalAtatus === "1" && (
                      <span className={`${prefixCls}-coworkList-line-pending`}>
                        【{getLabel(2242, "待审批")}】
                      </span>
                    )}
                    {name}
                    {isTop === "1" && renderIsTop}
                  </span>
                  {labelBycoworkList &&
                    labelBycoworkList.length !== 0 &&
                    labelBycoworkList.map((v, index) => {
                      return (
                        <Tag
                          key={index}
                          style={{
                            color:
                              v.labelColor === ""
                                ? "#333"
                                : getFontColorFromBgHex(v.labelColor),
                            background: v.labelColor,
                          }}
                        >
                          {v.labelName}
                        </Tag>
                      );
                    })}
                  <span className={`${prefixCls}-coworkList-line-lastTime`}>
                    {getLabel(83227, "最后发表")}：{lastdiscussantspan}
                  </span>
                </div>
                {important === "1" && (
                  <div className={`${prefixCls}-coworkList-line-star`}>
                    <Icon type="blog-xing" size="xs" />
                  </div>
                )}
              </div>
            );
          },
        },
      ],
    };
    return newTemp;
  };

  onSearchBarFocus = () => {
    const {
      history,
      communicationStore: { coworkSearchPageStore, localeStorageKey },
    } = this.props;
    history.push(coworkSearchPageStore.path);
    let searchHistory = localStorage.getItem(localeStorageKey);
    searchHistory = searchHistory ? JSON.parse(searchHistory) : [];
    coworkSearchPageStore.list.setState({ data: searchHistory });
  };

  onSearchPageChange = (val) => {
    const {
      communicationStore: { setStoreState, coworkAdSearchStore },
    } = this.props;
    setStoreState({ coworkSearchValue: val });
    coworkAdSearchStore.form.updateFields({ name: { value: val } });
  };

  onSearchAdvancedChange = (c, value) => {
    const { communicationStore } = this.props;
    if (c.domkey[0] === "name") {
      communicationStore.setStoreState({ coworkSearchValue: value });
    } else if (c.domkey[0] === "jointype") {
      communicationStore.setStoreState({ coworkJoinType: value });
    }
  };

  onSelectChange = ({ key }) => {
    const {
      communicationStore: {
        setStoreState,
        coworkAdSearchStore,
        onSearch,
        coworkChangeJoinType,
      },
    } = this.props;
    setStoreState({ coworkJoinType: key });
    coworkAdSearchStore.form.updateFields({ jointype: { value: key } });
    coworkChangeJoinType({ joinType: key });
    onSearch();
  };

  onSearch = () => {
    const {
      communicationStore: {
        coworkJoinType,
        coworkAdSearchStore,
        setStoreState,
        onSearch,
      },
    } = this.props;
    const { jointype } = coworkAdSearchStore.form.formParams;
    if (jointype !== coworkJoinType) {
      setStoreState({ coworkJoinType: jointype });
    }
    onSearch();
  };

  render() {
    const { prefixCls, communicationStore, history } = this.props;
    const {
      visible,
      showCheck,
      setStoreState,
      batchMark,
      path,
      onHideCheck,
      activePage,
      coworkAdSearchStore,
      coworkListStore,
      coworkSearchPageStore,
      coworkSearchValue,
      searchPageClear,
      coworkJoinType,
      coworkLoading,
    } = communicationStore;
    const {
      selectedRowKeys,
      isSelectedAll,
      haveCheck,
      data,
      loading,
    } = coworkListStore;
    const compare = compareParams(
      toJS(coworkAdSearchStore.form.formData),
      toJS(coworkAdSearchStore.form.defaultValues)
    );
    const adType = compare ? "filter-o" : "filter-o-hot";
    const searchBarProps = {
      placeholder: getLabel(390654, "请输入主题"),
      extraButton: [
        {
          key: "searchAd",
          show: (
            <Link to={coworkAdSearchStore.path}>
              <Icon type={adType} />{" "}
            </Link>
          ),
        },
        {
          key: "drop",
          show: (
            <Popover
              mask
              visible={visible}
              overlay={[
                <Popover.Item>{getLabel(27411, "新建协作")}</Popover.Item>,
                <Popover.Item>{getLabel(-81342, "标签管理")}</Popover.Item>,
                <Popover.Item>{getLabel(390705, "批量标记")}</Popover.Item>,
              ]}
              onSelect={this.onSelect}
              onVisibleChange={(visible) => setStoreState({ visible })}
            >
              <Icon key="ellipsis" type="ellipsis" />
            </Popover>
          ),
        },
      ],
    };
    const buttonGroupData = [
      {
        key: "submit",
        text: getLabel(390705, "批量标记"),
        onClick: () => {
          batchMark(() =>
            history.push({
              pathname: `${path}/tag`,
              state: {
                id: toJS(communicationStore.selectedListPageStore),
                page: "list",
              },
            })
          );
        },
        type: "primary",
      },
    ];
    let getSwipeActionProps = () => ({
      right: [
        {
          text: `${getLabel(25418, "标记")}`,
          onPress: (data) => {
            history.push({
              pathname: `${path}/tag`,
              state: {
                id: data.id,
                page: "view",
                labelList: JSON.parse(data.id_strspan),
              },
            });
          },
          className: `${prefixCls}-coworkList-mark`,
        },
      ],
    });

    const communicationClass = classnames({
      [`${prefixCls}`]: activePage === "communication",
      [`${prefixCls}-centerPage`]: activePage !== "communication",
    });
    const options = [
      { key: "0", showname: getLabel(83228, "全部主题") },
      { key: "6", showname: getLabel(382246, "仅参与的") },
      { key: "3", showname: getLabel(382247, "仅负责的") },
      { key: "1", showname: getLabel(382248, "负责或参与的") },
      { key: "4", showname: getLabel(83233, "我创建的") },
      { key: "5", showname: getLabel(83234, "待审批的") },
      { key: "7", showname: getLabel(17691, "直接参与的工作") },
      { key: "2", showname: getLabel(17692, "其他关注的") },
    ];
    let content = null;
    if (coworkLoading) {
      content = renderLoading;
    } else if (data.length === 0) {
      if (loading) {
        content = renderLoading;
      } else {
        content = renderNoData;
      }
    } else {
      content = (
        <ListViewPage.Normal
          store={coworkListStore}
          getTemplate={this.getTemplate}
          showCheck={showCheck}
          withSwipeAction
          swipeActionProps={getSwipeActionProps()}
          onRowClick={(v) => {
            !showCheck && this.toDetailCowork(v);
          }}
          isRowClickCheck={showCheck}
          customHeight="100%"
        />
      );
    }

    return (
      <div className={communicationClass}>
        <SearchBar
          value={coworkSearchValue}
          showExtraButton
          {...searchBarProps}
          onFocus={this.onSearchBarFocus}
        />
        <CustomSelect
          value={coworkJoinType}
          options={options}
          onChange={this.onSelectChange}
        />
        {showCheck && (
          <div className="cowork-template-top">
            <span className="cowork-template-top-cancel" onClick={onHideCheck}>
              {getLabel(201, "取消")}
            </span>
            <span>
              {getLabel(31503, "已选择")}
              {selectedRowKeys.length}
              {getLabel(390706, "条协作")}
            </span>
            {!isSelectedAll ? (
              <span
                className="cowork-template-top-all"
                onClick={() => haveCheck && coworkListStore.selectAll()}
              >
                {getLabel(556, "全选")}
              </span>
            ) : (
              <span
                className="cowork-template-top-all"
                onClick={() => haveCheck && coworkListStore.selectNone()}
              >
                {getLabel(387379, "取消全选")}
              </span>
            )}
          </div>
        )}
        <div
          className={`${communicationClass}-content ${showCheck && "checked"}`}
        >
          <BackTop
            visibilityHeight="200"
            modal
            target="wm-list-view-page-modal-scrollview"
          >
            {content}
          </BackTop>
        </div>
        {showCheck && (
          <div className={`${communicationClass}-buttonGroup`}>
            <ButtonGroup data={buttonGroupData} />
          </div>
        )}
        <RouteModal />
        <SearchAdvanced
          store={coworkAdSearchStore}
          onChange={this.onSearchAdvancedChange}
          onSubmit={this.onSearch}
          onReset={this.onSearchAdvancedReset}
        />
        <SearchPage
          store={coworkSearchPageStore}
          placeholder={getLabel("0", "请输入关键字")}
          searchValue={coworkSearchValue}
          rowKey="key"
          nameKey="name"
          onSubmit={this.onSearch}
          onChange={this.onSearchPageChange}
          onClear={searchPageClear}
        />
      </div>
    );
  }
}
